package com.chinafree.common.PDF;

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.color.DeviceRgb;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.Border;
import com.itextpdf.layout.border.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

import java.util.Date;


public class PdfEventHandler implements IEventHandler {

    private String header;
    private int x, y;


    Color gray = new DeviceRgb(232, 232, 232);
    Color green = new DeviceRgb(33, 125, 91);

    public PdfEventHandler(String header, int x, int y) {
        this.header = header;
        this.x = x;
        this.y = y;
    }

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Document document = new Document(pdfDoc);
        PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);

        buildTop(document);


        pdfCanvas.moveTo(40, 842 - 50);
        pdfCanvas.moveTo(595 - 40, 842 - 50);
        pdfCanvas.setColor(Color.BLACK, true);
        Rectangle area = page.getPageSize();
        int pageHeight = (int) area.getHeight();
        Canvas canvas = new Canvas(pdfCanvas, pdfDoc, area);
//        canvas.showTextAligned(header, 30, 842 - 50, TextAlignment.LEFT);
    }

    public void buildTop(Document document) {

        Table table = new Table(new float[]{250, 270});
        table.setFixedPosition(40,842-40,520);
        table.setBorderBottom(new SolidBorder(gray, 1));
        //1.
        Cell cell = new Cell();
        cell.add("hiredFree");
        cell.setFontSize(14);
        cell.setFontColor(green);
        cell.setBorder(Border.NO_BORDER);
        cell.setHorizontalAlignment(HorizontalAlignment.LEFT);
        table.addCell(cell);


        //2.time
        Cell cell1 = new Cell();
        cell1.add(new Date().toString());
        cell1.setFontSize(8);
        cell1.setFontColor(Color.BLACK);
        cell1.setBorder(Border.NO_BORDER);
        cell1.setTextAlignment(TextAlignment.RIGHT);
        cell1.setVerticalAlignment(VerticalAlignment.BOTTOM);
        table.addCell(cell1);
        document.add(table);



    }
}